package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void add(DishDTO dishDTO) {
        //1、将dishDTO转换成dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //2、设置默认字段
        if(ObjectUtils.isEmpty(dish.getStatus())){
            dish.setStatus(StatusConstant.ENABLE);
        }

        //3、将dish新增至数据库
        dishMapper.save(dish);

        //4、保存口味数据
        saveDishFlavor(dishDTO, dish);
    }

    private void saveDishFlavor(DishDTO dishDTO, Dish dish) {
        //1、获取口味数据，并且填充每个口味的菜品ID
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(ObjectUtils.isNotEmpty(flavors)){
            flavors.forEach(f -> f.setDishId(dish.getId()));
        }

        //2、批量新增口味数据
        dishFlavorMapper.batchSave(flavors);
    }

    /**
     * 分页查询
     *
     * @param queryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO queryDTO) {
        //1、利用PageHelper设置分页参数
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());

        //2、发起分页查询
        Page<DishVO> page = dishMapper.page(queryDTO);

        //3、将查询结果封装成PageResult并返回
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据ID集合批量删除
     *
     * @param ids
     */
    @Transactional
    @Override
    public void batchDelete(List<Long> ids) {
        // 1、校验是否有起售中的菜品，如果有，不能删
        Integer count = dishMapper.countEnableByIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        // 2、校验是否有被套餐关联的菜品，如果有，不能删
        count = setmealMapper.countByDishIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 3、删除菜品
        dishMapper.batchDelete(ids);

        // 4、删除菜品关联的 Flavor
        dishFlavorMapper.batchDeleteByDishIds(ids);
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        return dishMapper.getByIdWithFlavor(id);
    }

    /**
     * 根据ID修改菜品信息
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //1、将dto转换成entity
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //2、修改菜品信息
        dishMapper.update(dish);

        //3、修改菜品关联的flavor信息（先删后增）
        dishFlavorMapper.batchDeleteByDishIds(List.of(dishDTO.getId()));

        //4、保存口味数据
        saveDishFlavor(dishDTO, dish);
    }

    /**
     * 启售停售
     *
     * @param id
     * @param status
     */
    @Override
    public void startOrStop(Long id, Integer status) {
        final Dish dish = Dish.builder().id(id).status(status).build();
        this.dishMapper.update(dish);
    }

    /**
     * 根据查询条件查询
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> list(Dish dish) {
        return dishMapper.list(dish);
    }

}
